class xT_AICommand_Cmd_MoveForLeader extends xT_AICommand_Cmd_Move;

//=============================================================================
// Variables: Movement
//=============================================================================
var private Actor                       Leader;

//=============================================================================
// Events
//=============================================================================
event Popped()
{
	ScriptedMoveTarget = none;
	StopLatentExecution();
	Pawn.ZeroMovementVariables();
}

//=============================================================================
// State
//=============================================================================
AUTO state FollowLeader 
{
Begin:
	//`log("xT_AICommand_FollowLeader executed");

	if (Leader == none)
	{
		Sleep(WorldInfo.DeltaSeconds);
		Goto('Begin');
	}	

	ScriptedMoveTarget = Leader;

Following:
	// while we have a valid pawn and move target, and we haven't reached the target yet
	if (abs(VSize(Leader.Location - Pawn.Location))>256) 
	{
		if( GeneratePathToActor(Leader) )
		{
			NavigationHandle.SetFinalDestination(ScriptedMoveTarget.Location);

			while( Pawn != None && ScriptedMoveTarget != None && !Pawn.ReachedDestination(ScriptedMoveTarget) )
			{				
				if( NavigationHandle.ActorReachable( ScriptedMoveTarget) )
				{
					// then move directly to the actor
					MoveToward( ScriptedMoveTarget, ScriptedFocus, Pawn.GetCollisionRadius() * UnitsInMove, true, false );
				}
				else
				{
					// move to the first node on the path
					if( NavigationHandle.GetNextMoveLocation( TempDest, Pawn.GetCollisionRadius() * UnitsInMove) )
					{
						if (!NavigationHandle.SuggestMovePreparation(TempDest, Outer))
						{
							MoveTo( TempDest, ScriptedFocus, Pawn.GetCollisionRadius() * UnitsInMove, false );						
						}
					}
				}
			}
		}
		else
		{
			//give up because the nav mesh failed to find a path
			`warn("FindNavMeshPath failed to find a path to"@ScriptedMoveTarget);
			ScriptedMoveTarget = None;
		}   
	}
	Pawn.ZeroMovementVariables();
	Sleep(WorldInfo.DeltaSeconds);

	while (true) Goto('Following');

	PopCommand(Self);
}

//=============================================================================
// Setting up Leader unit
//=============================================================================
function SetLeader(xT_Pawn aLeader, int aUnitsInMove)
{
	Leader = aLeader;
	UnitsInMove = aUnitsInMove;
}

//=============================================================================
// DefaultProperties
//=============================================================================
defaultproperties
{
}
